#include "player.h"
#include "common.h"
#include "gun/gun.h"

namespace fireplane
{
	static Player* _s_Player = NULL;
	Player::Player():
		_speed(300),
		_need_move(false)
	{
		_dir = ccp(0,0);

		_s_Player = this;
	}

	Player::~Player()
	{
		_s_Player = NULL;
	}

	void Player::init(CCPoint pos)
	{
		_body = Common::createSpriteByFrameName("longdi.png");
		addChild(_body);

		this->setContentSize(_body->getContentSize());
		this->setPosition(pos);
		_despos = pos;

		Gun::CreateNormalGun arg(Gun::GT_normal_gun);
		arg.tdir = ccp(0,1);
		arg.tspeed = 800;
		arg.o = Bullet::BO_PLAYER;
		arg.pos = ccp(0,10);

		_gun = Gun::createGun(&arg);
		addChild(_gun);

		_fireDelay = 0;

		scheduleUpdate();
	}

	void Player::_do_fire_logic(float dt)
	{
		_fireDelay += dt;
		if (_fireDelay > 0.1f)
		{
			_fireDelay = 0;
			_gun->fire(Bullet::BI_img0);
		}
	}

	void Player::_do_move_logic(float dt)
	{
		if (_need_move)
		{
			CCPoint pos = this->getPosition();

			_dir = ccpSub(_despos,pos);
			_dir = ccpNormalize(_dir);
			CCPoint mov = ccpMult(_dir,dt * _speed);
			pos = ccpAdd(pos,mov);

			this->setPosition(pos);
		}
	}

	void Player::update( float dt )
	{
		_do_fire_logic(dt);
		_do_move_logic(dt);
	}

	void Player::beginTouch( CCPoint worldPos )
	{
		_despos = this->getParent()->convertToNodeSpace(worldPos);
		_need_move = true;
	}

	void Player::moveTouch( CCPoint worldPos )
	{
		_despos = this->getParent()->convertToNodeSpace(worldPos);
	}

	void Player::endTouch( CCPoint worldPos )
	{
		_despos = this->getPosition();
		_need_move = false;
	}

	Player* Player::getMainPlayer()
	{
		return _s_Player;
	}

	CCNode* Player::getPlayerParent()
	{
		return getParent();
	}

	cocos2d::CCPoint Player::getPlayerPos()
	{
		return this->getPosition();
	}

	CCRect Player::getPlayerWorldCollisionSize()
	{
		CCSize size = _body->getContentSize();
		CCAffineTransform tan = _body->nodeToWorldTransform();
		size = CCSizeApplyAffineTransform(size,tan);

		CCPoint pos = ccp(0,0);
		pos = CCPointApplyAffineTransform(pos,tan);

		return CCRectMake(pos.x,pos.y,size.width,size.height);
	}

}